package com.loopj.ohos.http.sample;


import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.AsyncHttpResponseHandler;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.ResponseHandlerInterface;

import java.util.Locale;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import ohos.utils.PlainArray;

/**
 * ThreadingTimeoutSample
 */
public class ThreadingTimeoutSample extends SampleParentAbility {

    private static final String LOG_TAG = "ThreadingTimeoutSample";
    /**
     * states
     */
    protected final PlainArray<String> states = new PlainArray<String>();
    /**
     * states
     */
    protected int counter = 0;

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_threading_timeout;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    @Override
    public boolean isRequestHeadersAllowed() {
        return false;
    }

    @Override
    public boolean isCancelButtonAllowed() {
        return true;
    }

    @Override
    public String getDefaultURL() {
        return PROTOCOL + "httpbin.org/delay/6";
    }

    /**
     * setStatus
     *
     * @param id setStatus
     * @param status setStatus
     */
    protected synchronized void setStatus(int id, String status) {
        String current = states.get(id, null);
        states.put(id, current == null ? status : current + "," + status);
        clearOutputs();
        for (int i = 0; i < states.size(); i++) {
            debugResponse(LOG_TAG, String.format(Locale.US, "%d (from %d): %s", states.keyAt(i), getCounter(), states.get(states.keyAt(i))));
        }
    }

    @Override
    public ResponseHandlerInterface getResponseHandler() {
        return new AsyncHttpResponseHandler() {

            private final int id = counter++;

            @Override
            public void onStart() {
                setStatus(id, "START");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                setStatus(id, "SUCCESS");
            }

            @Override
            public void onFinish() {
                setStatus(id, "FINISH");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                setStatus(id, "FAILURE");
            }

            @Override
            public void onCancel() {
                setStatus(id, "CANCEL");
            }
        };
    }

    public int getCounter() {
        return counter;
    }

    @Override
    public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) {
        return client.get(this, URL, headers, null, responseHandler);
    }
}